//
//  JXLoginController.m
//  JiaoX
//
//  Created by jiaoxiu－005 on 15/1/6.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//  登录

#import "JXLoginController.h"
#import "OauthLoginBtn.h"
#import "JXBaseRequest.h"
#import "SelfDataTool.h"
#import "LoginRes.h"
#import "UserDefaultsHelper.h"
#import "JXMineController.h"
#import "JXForgetPwdController.h"
#import "AppDelegate.h"
#import "JXTabBarController.h"
#import "WeChatLoginRes.h"
#import "WeChatUtil.h"
#import "WeChatUserinfoRes.h"
#import "TalkingDataAppCpa.h"

@interface JXLoginController ()<TencentSessionDelegate>

@property(nonatomic,strong)TencentOAuth *tencentOAuth;
@property(nonatomic,strong)NSArray  *permission;


@property (nonatomic, strong) UITextField *userName;
@property (nonatomic, strong) UITextField *passWord;
@property (nonatomic, strong)  UIButton *login;
@property (nonatomic, strong)  UIButton *forgetButton;
@property (nonatomic, strong)  UILabel *centerLabel;
@property (nonatomic, strong)  UIImageView *leftLineImg;

@end

@implementation JXLoginController

- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化腾讯相关
    [self initTencent];
    //注册第三方登录状态的通知
    [[NSNotificationCenter defaultCenter] addObserver: self selector:@selector(oauthLoginCallBack:)name:@"oauth_login" object:nil];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    //初始化用户名输入框
    [self initUsernameTextField];
    //初始化密码输入框
    [self initPasswordTextField];
    //登录按钮
    [self initLoginButton];
    //忘记密码
    [self initForgetPwd];
    //第三方登录分割线
    [self initLine];
    //初始化第三方的登录
    [self initOauthLogin];
}

/**
 *  初始化腾讯相关
 */
-(void)initTencent{
    _tencentOAuth = [[TencentOAuth alloc]initWithAppId:QQ_APP_ID andDelegate:self];
    _permission = [NSArray arrayWithObjects:kOPEN_PERMISSION_GET_INFO,kOPEN_PERMISSION_GET_USER_INFO,kOPEN_PERMISSION_GET_SIMPLE_USER_INFO, nil];
}


/**
 *  初始化用户名输入框
 */
-(void)initUsernameTextField{
    UITextField *userName = [[UITextField alloc]init];
    //frame
    CGFloat userNameX = JXPublicInset;
    CGFloat userNameY = 20;
    CGFloat userNameW = JXScreenW-JXPublicInset*2;
    CGFloat userNameH = 46.5;
    CGRect rect =  CGRectMake(userNameX, userNameY, userNameW, userNameH);
    [self initTextField:self.view edit:userName frame:rect placeholderText:@"手机号"];
    self.userName = userName;
}

/**
 *  初始化密码输入框
 */
-(void)initPasswordTextField{
    UITextField *passWord = [[UITextField alloc]init];
    //frame
    CGFloat passwordX = JXPublicInset;
    CGFloat passwordY = CGRectGetMaxY(self.userName.frame)+10;
    CGFloat passwordW = JXScreenW-JXPublicInset*2;
    CGFloat passwordH = 46.5;
    passWord.secureTextEntry=YES;//设置成密码格式
    CGRect rect =  CGRectMake(passwordX, passwordY, passwordW, passwordH);
    [self initTextField:self.view edit:passWord frame:rect placeholderText:@"密码"];
    self.passWord =passWord;
}

/**
 *  初始化登录button
 */
-(void)initLoginButton{
    UIButton *login =[[UIButton alloc]init];
    [login.titleLabel setFont:[UIFont systemFontOfSize:[DimensUtils getScaleX:15]]];
    [login setTitle:@"立即登录" forState:UIControlStateNormal];
    [login setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [login setContentMode:UIViewContentModeCenter];
    login.frame = CGRectMake(JXPublicInset, CGRectGetMaxY(self.passWord.frame)+20, JXScreenW-JXPublicInset*2,  46.5);
    [login setBackgroundImage:[UIImage resizedImage:@"btn_login_bg"] forState:UIControlStateNormal];
    [login addTarget:self action:@selector(loginDid) forControlEvents:UIControlEventTouchUpInside];
    self.login = login;
    [self.view addSubview:login];
}

/**
 * 忘记密码
 */
-(void)initForgetPwd{
    UIButton *forgetButton = [[UIButton alloc]init];
    forgetButton.backgroundColor = [UIColor clearColor];
    NSString *text = @"忘记密码？";
    [forgetButton setTitle:text forState:UIControlStateNormal];
    [forgetButton.titleLabel setFont:[UIFont systemFontOfSize:[DimensUtils getScaleX:12]]];
    [forgetButton setTitleColor:JXColor(51, 144, 248) forState:UIControlStateNormal];
    CGSize titleSize = [text sizeWithFont:forgetButton.titleLabel.font];
    forgetButton.frame = CGRectMake(JXScreenW-10-titleSize.width, CGRectGetMaxY(self.login.frame)+10, titleSize.width, titleSize.height);
    [forgetButton addTarget:self action:@selector(forgetPwdDid) forControlEvents:UIControlEventTouchUpInside];
    self.forgetButton = forgetButton;
    [self.view addSubview:forgetButton];
}

/**
 *  初始化分割线
 */
-(void)initLine{
    NSString *centerText =@"一键登录";
    //后面的线
    UIImageView *leftLineImg = [[UIImageView alloc]init];
    UIImage *centerImg =[UIImage imageNamed:@"login_oauth_line"];
    [leftLineImg setImage:centerImg];
    leftLineImg.frame = CGRectMake(0, CGRectGetMaxY(self.forgetButton.frame)+28, JXScreenW, 1);
    //中间文字
    UILabel *centerLabel = [[UILabel alloc]init];
    centerLabel.backgroundColor = [UIColor whiteColor];
    [centerLabel setText:centerText];
    centerLabel.textAlignment = NSTextAlignmentCenter;
    [centerLabel setFont:[UIFont systemFontOfSize:[DimensUtils getScaleX:12]]];
    [centerLabel setTextColor:JXColor(77, 77, 77)];
    CGSize centerTitleSize = [centerText sizeWithFont:centerLabel.font];
    centerLabel.frame = CGRectMake(JXScreenW*0.5-centerTitleSize.width/2-10, CGRectGetMaxY(self.forgetButton.frame)+20, centerTitleSize.width+10, centerTitleSize.height);
    self.centerLabel = centerLabel;
    self.leftLineImg = leftLineImg;
    [self.view addSubview:leftLineImg];
    [self.view addSubview:centerLabel];
}

/**
 *  初始化第三方登录
 */
-(void)initOauthLogin{
    //微信登录
    if ([WXApi isWXAppInstalled]) {
        //如果安装了微信
        OauthLoginBtn *wxLogin = [[OauthLoginBtn alloc]init];
        UIImage *wxImg = [UIImage imageNamed:@"login_wx_icon"];
        CGRect wxrect = CGRectMake((JXScreenW/2-wxImg.size.width)/2, CGRectGetMaxY(self.centerLabel.frame)+15, wxImg.size.width, wxImg.size.height+40);
        [self initOauthLoginButton:wxLogin img:wxImg title:@"微信" frame:wxrect target:@selector(wxLogin)];
    }
    
    
    if ([TencentOAuth iphoneQQInstalled]) {
        //如果安装了手机QQ
        OauthLoginBtn *qqLogin = [[OauthLoginBtn alloc]init];
        UIImage *qqImg = [UIImage imageNamed:@"login_qq_icon"];
        CGFloat qqLoginX = (JXScreenW*0.5-qqImg.size.width)/2+JXScreenW/2;
        if (![WXApi isWXAppInstalled]) {
            qqLoginX = (JXScreenW/2-qqImg.size.width)/2;
        }
        CGRect qqrect = CGRectMake(qqLoginX, CGRectGetMaxY(self.centerLabel.frame)+15, qqImg.size.width, qqImg.size.height+40);
        [self initOauthLoginButton:qqLogin img:qqImg title:@"QQ" frame:qqrect target:@selector(qqLogin)];
    }
    
    if (![TencentOAuth iphoneQQInstalled] && ![WXApi isWXAppInstalled]) {
        [self.centerLabel removeFromSuperview];
        [self.leftLineImg removeFromSuperview];
    }
    
    
//    //微博登录
//    OauthLoginBtn *wbLogin = [[OauthLoginBtn alloc]init];
//    UIImage *wbImg = [UIImage imageNamed:@"login_wb_icon"];
//    CGRect wbrect = CGRectMake(JXScreenW-qqImg.size.width-10, CGRectGetMaxY(self.centerLabel.frame)+15, wbImg.size.width, wbImg.size.height+40);
//    [wbLogin setHidden:YES];
//    [self initOauthLoginButton:wbLogin img:wbImg title:@"微博" frame:wbrect target:@selector(wbLogin)];
    
}

/**
 *  初始化第三方登录的btn
 *
 *  @param btn    btn
 *  @param img    图片
 *  @param title  描述
 *  @param frame  frame
 *  @param target target
 */
-(void) initOauthLoginButton:(OauthLoginBtn *)btn img:(UIImage *)img title:(NSString *)title frame:(CGRect)frame target:(SEL)target{
    btn.backgroundColor = [UIColor clearColor];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setImage:img forState:UIControlStateNormal];
    [btn.titleLabel setFont:[UIFont systemFontOfSize:15]];
    [btn setTitleColor:JXColor(204, 204, 204) forState:UIControlStateNormal];
    btn.frame = frame;
    [btn addTarget:self action:target forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}

/**
 *  初始化输入框 TextField
 */
-(void)initTextField :(UIView *)container edit:(UITextField *)edit frame:(CGRect)frame placeholderText:(NSString *)placeholderText{
    //设置边框
    [edit.layer setBorderColor:JXColor(204, 204, 204).CGColor];
    [edit.layer setBorderWidth:0.7];
    [edit.layer setCornerRadius:5];
    
    edit.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    edit.attributedPlaceholder =[[NSAttributedString alloc] initWithString:placeholderText attributes:@{NSForegroundColorAttributeName: JXColor(204, 204, 204)}];
    edit.frame = frame;
    edit.clearButtonMode = UITextFieldViewModeAlways;
    [self textFieldAddleftView:edit];
    [container addSubview:edit];
}

/**
 *  输入框添加左边距
 *
 *  @param edit
 */
-(void)textFieldAddleftView:(UITextField *)edit{
    //输入框添加左边距
    CGRect frame = [edit frame];
    frame.size.width = 7.0f;
    UIView *leftview = [[UIView alloc] initWithFrame:frame];
    edit.leftViewMode = UITextFieldViewModeAlways;
    edit.leftView = leftview;
}

/**
 *  点击登录按钮
 */
-(void)loginDid{
    NSString *username = self.userName.text;
    NSString *password = self.passWord.text;
    if([Utils isBlankString:username]){
        [DialogUtils showTipsWithView:self.view String:@"用户名不能为空"];
        return;
    }
    if([Utils isBlankString:password]){
        [DialogUtils showTipsWithView:self.view String:@"密码不能为空"];
        return;
    }
    [self login :username password:password];
}

/**
 *  执行登录
 */
-(void) login:(NSString *)username password:(NSString *)password{
    JXBaseRequest *request = [[JXBaseRequest alloc]init];
    NSDictionary *dic = [request keyValues];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:dic];
    [params setObject:username forKey:@"username"];
    [params setObject:password forKey:@"password"];
    MBProgressHUD *loding = [DialogUtils showLoadingWithView:self.view];
    [SelfDataTool loginDataInfoWithParam:params success:^(LoginRes *result) {
        [loding hide:YES];
        if([Utils isBlankString:[result data]]){//登录成功，保存token和secret
            [DialogUtils showTipsWithView:self.view String:@"登录成功"];
            //清除隐私保护密码
            [self clearPrivacyPwd];
            [self resolveLoginParams:result];
        }else{//登录失败
            [DialogUtils showTipsWithView:self.view String:[result data]];
            JXLog(@"登录失败:%@",[result data]);
        }
    } failure:^(NSError *error) {
        [loding hide:YES];
        [DialogUtils showTipsWithView:self.view String:@"登录失败"];
        JXLog(@"failure登录失败:%@",error);
    }];
}

-(void)clearPrivacyPwd{
    AppDelegate *myDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if (myDelegate.isClearPrivacyPwd) {
        [UserDefaultsHelper setObject:nil forKey:KEY_HAVE_PASSWORD];
    }
}

/**
 *  处理登录成功的参数
 *
 *  @param result
 */
-(void)resolveLoginParams:(LoginRes *)result{
    NSString *token =  result.token;
    NSString *secret = result.screatKey;
    JXLog(@"screatKey : %@-----------token : %@",secret,token);
    [self saveBasePrams:token :secret];
    //TODO 1.提交本地购物车的数据
    //2.获取用户信息
    [self getUserInfo];
}

/**
 *  获取用户信息
 */
-(void) getUserInfo{
    [SelfDataTool getUserInfoWithUserId:@"" success:^(UserInfo *result) {
        if([Utils isBlankString:[result data]]){//获取用户信息成功
            //登录成功，获取个人信息完毕之后设置talkinig data事件
            [TalkingDataAppCpa onLogin:@"Your_userId"];
            //1.保存用户信息
            [Utils saveUserInfo:result];
            //2.判断是直接关闭当前页面，还是跳转到MainTabAct(隐私)
            AppDelegate *myDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            if (myDelegate.isClearPrivacyPwd) {
                myDelegate.isClearPrivacyPwd = NO;
                //直接前往tabcontroller
                UIWindow *window = [UIApplication sharedApplication].keyWindow;
                window.rootViewController = [[JXTabBarController alloc]init];
                [window makeKeyAndVisible];
            }else{
                [self back];
            }
        }
    } failure:^(NSError *error) {//获取用户信息失败
        JXLog(@"获取用户信息失败:%@",error);
    }];
}

/**
 *  保存token ,secret
 *
 *  @param token
 *  @param secret
 */
-(void)saveBasePrams:(NSString *)token :(NSString *)secret{
    if(![Utils isBlankString:token]){
        [UserDefaultsHelper setObject:token forKey:KEY_APPTOKEN];
    }
    if(![Utils isBlankString:secret]){
        [UserDefaultsHelper setObject:secret forKey:KEY_SERVER_SECRET_KEY];
    }
}
/**
 *  忘记密码
 */
-(void) forgetPwdDid{
    UIViewController *c = [self.view.superview viewController];
    [c.navigationController pushViewController:[[JXForgetPwdController alloc]init] animated:true];
}
/**
 *  微信登录
 */
-(void) wxLogin{
    [WeChatUtil sendAuthRequest];
}
/**
 *  qq登录
 */
-(void) qqLogin{
    if(![_tencentOAuth isSessionValid]){//2.登录时，调用TencetnOAuth对象的authorize方法：
        [_tencentOAuth authorize:_permission inSafari:NO];
        [_tencentOAuth authorize:_permission];
    }
}
/**
 *  微博登录
 */
-(void) wbLogin{
    JXLog(@"wbLogin");
}

/**
 *  第三方登录回调
 */
-(void)oauthLoginCallBack:(NSNotification*)aNotification
{
    WeChatUserinfoRes *loginRes = [aNotification object];
    JXBaseRequest *request = [[JXBaseRequest alloc]init];
    NSDictionary *dic = [request keyValues];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:dic];
    [params setObject:loginRes.unionid forKey:@"unionid"];
    [params setObject:loginRes.nickname forKey:@"nickname"];
    [params setObject:[NSString stringWithFormat:@"%ld",(long)loginRes.sex] forKey:@"userGender"];
    [params setObject:loginRes.headimgurl forKey:@"userImg"];
    [params setObject:loginRes.clientType forKey:@"clientType"];
    MBProgressHUD *loding = [DialogUtils showLoadingWithView:self.view];
    [SelfDataTool oauthLoginWithParam:params success:^(LoginRes *result) {
        [loding setHidden:YES];
        if([Utils isBlankString:result.data]){//第三方登录成功
            [DialogUtils showTipsWithView:self.view String:@"登录成功"];
            //退出qq
            [_tencentOAuth logout:self];
            //清除隐私保护密码
            [self clearPrivacyPwd];
            //保存返回的参数
            [self resolveLoginParams:result];
        }else{
            [DialogUtils showTipsWithView:self.view String:@"登录失败"];
        }
    } failure:^(NSError *error) {
        [loding setHidden:YES];
        [DialogUtils showTipsWithView:self.view String:@"登录失败"];
    }];
    
    JXLog(@"第三方登录返回%@",loginRes);
}

/**
 *  返回按钮
 */
-(void)back{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    
    UIViewController *c = [self.view.superview viewController];
    [c dismissViewControllerAnimated:NO completion:^{
    }];
}



//----------------qq login start------------------
-(void)getUserInfoResponse:(APIResponse *)response{//获取用户信息成功的回调
    NSString* nickname = [response.jsonResponse objectForKey:@"nickname"];
    NSString* gender = [response.jsonResponse objectForKey:@"gender"];
    NSString* headImg = [response.jsonResponse objectForKey:@"figureurl_qq_1"];
    WeChatUserinfoRes *result = [[WeChatUserinfoRes alloc]init];
    [result setUnionid:[_tencentOAuth openId]];
    [result setClientType:@"1"];
    [result setNickname:nickname];
    [result setHeadimgurl:headImg];
    if([gender isEqualToString:@"男"]){
        [result setSex:1];
    }else{
        [result setSex:2];
    }
    //把获取到的信息传输到登录回调请求服务器进行第三方登录
    [[NSNotificationCenter defaultCenter] postNotificationName:@"oauth_login" object:result];

    JXLog(@"qqlogin nickname = %@",nickname);
}

-(void)tencentDidLogin{//2. 登录完成后，会调用TencentSessionDelegate中关于登录的协议方法。
    
    if (_tencentOAuth.accessToken && 0 != [_tencentOAuth.accessToken length]){  // 登录成功：记录登录用户的OpenID、Token以及过期时间
        //3. 登录成功后，即可获取到access token和openid。accessToken和 openid保存在TencentOAuth对象中。可以通过相应的属性方法直接获得。
        NSString *qqAccessToken = [_tencentOAuth accessToken];
        NSString *qqOpenId = [_tencentOAuth openId];
        NSDate *qqExpirationDate = [_tencentOAuth expirationDate] ;
        JXLog(@"token = %@,openid = %@,date = %@",qqAccessToken,qqOpenId,qqExpirationDate);
        BOOL result = [_tencentOAuth getUserInfo];
        if(result){
            [DialogUtils showTipsWithView:self.view String:@"获取用户信息成功"];
        }else{
            [DialogUtils showTipsWithView:self.view String:@"获取用户信息失败"];
        }
    }else{
        //登录不成功 没有获取accesstoken
        [DialogUtils showTipsWithView:self.view String:@"授权登录失败"];
    }
}

-(void)tencentDidNotLogin:(BOOL)cancelled{
    if (cancelled){
        //用户取消登录
        [DialogUtils showTipsWithView:self.view String:@"授权登录取消"];
    }else{
        //登录失败
        [DialogUtils showTipsWithView:self.view String:@"授权登录失败"];
    }
}

-(void)tencentDidNotNetWork{
    //无网络连接，请设置网络
    [DialogUtils showTipsWithView:self.view String:@"无网络连接"];
}

//----------------qq login end------------------


@end